<?php
/**
 * @author spenceryg
 * @date 2022/12/6
 * @time 12:38 下午
 * @focus love & life
 */


namespace app\common\lib\word;


use app\common\lib\word\model\WordCat;

class Word
{
    /**
     * getCat
     * @param $cat_name
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getCat($cat_name): array
    {
        $cats = WordCat::where('name', 'like', '%' . $cat_name . '%')->select();
        foreach ($cats as $cat) {
            $cat['count'] = \app\common\lib\word\model\Word::where('cat_id', $cat['id'])->count();
        }
        return $cats->isEmpty() ? [] : $cats->toArray();
    }


    /**
     * getCatWords
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getCatWords($id): array
    {
        $data = WordCat::with(['word'])->find($id);
        return $data->isEmpty() ? [] : $data->toArray();
    }


    /**
     * getCatWordsDemo
     * @param $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getCatWordsDemo($id): array
    {
        $data = \app\common\lib\word\model\Word::where('cat_id', $id)->limit(50)->select();
        return $data->isEmpty() ? [] : $data->toArray();
    }

    /**
     * 随机一个类目的数据
     * getRandomWordByCatId
     * @param $id
     * @return mixed
     */
    public static function getRandomWordByCatId($id)
    {
        $words = cache('lib_words_' . $id);
        if ($words) {
            $index = array_rand($words);
            return $words[$index];
        }
        $words = \app\common\lib\word\model\Word::where('cat_id', $id)->column('word');
        cache('lib_words_' . $id, $words, 3600);
        $index = array_rand($words);
        return $words[$index];
    }
}
